var indexObj = {
    init: function() {
        this.updateAccount();
        this.switch();
        this.eventAdd();
        this.getTableData();
        this.editEvent();
        this.pageEvent();
    },
    updateAccount: function() {
        var accountLi = document.getElementsByClassName('header')[0].getElementsByClassName('account')[0];
        // console.log(accountLi);
        var loginAccount = getCookie('account');
        if(loginAccount){
            accountLi.innerHTML = loginAccount;
        }else{
            window.location.href = './login.html';
        }
    },
    switch: function() {
        var dlEle = document.getElementsByTagName('dl')[0];
        // console.log(dlEle);
        var that = this;
        dlEle.onclick = function(e) {
            var event = e || window.event;
            var target = event.target || event.srcElement;
            if(target.nodeName == 'DD') {
                var itsSibling = that.getEleSibling(target);
                for(var i = 0; i < itsSibling.length; i ++) {
                    itsSibling[i].className = "";
                }
                target.className = 'active';
                var tagClass = target.getAttribute('data-class');
                // console.log(tagClass);
                var tagEle = document.getElementsByClassName(tagClass)[0];
                var tagEleSibling = that.getEleSibling(tagEle);
                for(var j = 0; j < tagEleSibling.length; j ++) {
                    tagEleSibling[j].style.display = 'none';
                }
                tagEle.style.display = 'block';
            }
        }
    },
    getEleSibling: function(ele) {
        var siblingArr = [];
        var siblingArrAll = ele.parentNode.children;
        for(var i = 0; i < siblingArrAll.length; i ++) {
            if(siblingArrAll[i] != ele) {
                siblingArr.push(siblingArrAll[i]);
            }
        }
        return siblingArr;
    },
    eventAdd: function() {
        var form = document.getElementsByClassName('add-student')[0];
        var subBtn = form.getElementsByTagName('button')[0];
        var that = this;
        subBtn.onclick = function(e) {
            var event = e || window.event;
            event.preventDefault();
            var stuInf = {  
                name: form.name.value,
                // 可以通过form. id || name 访问form下面的元素，如果有多个，返回类数组，里面带有value值
                sex: form.sex.value,
                email: form.email.value,
                sNo: form.num.value,
                birth: form.birth.value,
                phone: form.tel.value,
                address: form.addre.value
            };
            var bool = true;
            for(var prop in stuInf) {
                bool = bool && stuInf[prop];
            }
            if(bool) {
                // 学号必须为 4 - 16 位的数字
                var regSNo = /^\d{4,16}$/;
                if(regSNo.test(stuInf.sNo)){
                    // 校验出生年份 1920 - 2020
                    if(stuInf.birth >= 1920 && stuInf.birth <= 2020 && stuInf.birth.length == 4){
                        // 校验手机号
                        if(/^1\d{10}$/.test(stuInf.phone)){
                            ajax('GET', 'http://open.duyiedu.com/api/student/addStudent', that.dataConcat(stuInf), function(res){
                                // console.log(res);
                                if(res.status == 'success') {
                                    alert(res.msg);
                                    that.page = 1;
                                    that.getTableData();
                                    var dd = document.getElementsByTagName('dd')[0];
                                    // console.log(dd);
                                    dd.click();
                                    
                                }else{
                                    alert(res.msg);
                                }
                            }, true);
                        }else {
                            alert('请检查手机号是否正确');
                        }
                    }else{
                        alert('请检查出生年是否正确');
                    }
                }else{
                    alert('Sorry, 学号必须为 4 - 16 位的数字！');
                }
            }else{
                alert('表单填写不完整，请认真检查一下呀！');
            }
        }
    },
    dataConcat: function(dataObj) {
        var data = 'appkey=xiaobaibai_1590807635908';
        for(var prop in dataObj) {
            data = data + '&' + prop + '=' + dataObj[prop];
        }
        // console.log(data);
        return data;
    },
    tableData: [],
    page: 1,  // 返回第page页的学生信息
    size: 18,  // 每页包含多少个学生
    allPage: 1, // 一共有多少页，先给个初始值
    getTableData: function() {
        var that = this
        // var data = 'appkey=xiaobaibai_1590807635908';
        // ajax('GET', 'http://open.duyiedu.com/api/student/findAll', data, function(res){
        //     // console.log(res);
        //     if(res.status == 'success') {
        //         that.tableData = res.data
        //         that.renderTable(res.data);
        //     }else {
        //         alert(res.msg);
        //     }
        // }, true);

        //按页查询学生信息
        var data = 'appkey=xiaobaibai_1590807635908' + '&page=' + this.page + '&size=' + this.size;
        ajax('GET', 'http://open.duyiedu.com/api/student/findByPage', data, function(res){
            // console.log(res);
            if(res.status == 'success') {
                that.allPage = Math.ceil(res.data.cont / that.size);
                that.tableData = res.data.findByPage;
                that.renderTable(that.tableData);
            }else {
                alert(res.msg);
            }
        }, true);
    },
    pageEvent: function() {
        var preBtn = document.getElementById('pre-btn');
        var nextBtn = document.getElementById('next-btn');
        var that = this;
        // console.log(preBtn, nextBtn);
        nextBtn.onclick = function() {
            if(that.page < that.allPage){
                that.page ++;
                that.getTableData();
            }
        }
        preBtn.onclick = function() {
            if(that.page > 1) {
                that.page --;
                that.getTableData();
            }
        }
    },
    renderTable: function(studentData) {
        // console.log(studentData);
        var renderDom = document.getElementsByClassName('student-list')[0];
        // console.log(renderDom);
        var dataStr = `<ul class="list-top">
            <li>学号</li>
            <li>姓名</li>
            <li>性别</li>
            <li>邮箱</li>
            <li>年龄</li>
            <li>手机号</li>
            <li>住址</li>
            <li>操作</li>
        </ul>`;
        for(var i = 0; i < studentData.length; i ++) {
            dataStr += `<ul>
                <li>${studentData[i].sNo}</li>
                <li>${studentData[i].name}</li>
                <li>${studentData[i].sex == 0 ? '男' : '女'}</li>
                <li>${studentData[i].email}</li>
                <li>${new Date().getFullYear() - studentData[i].birth}</li>
                <li>${studentData[i].phone}</li>
                <li>${studentData[i].address}</li>
                <li>
                    <button type="button" data-index="${i}" data-log="edit">编辑</button>
                    <button type="button" data-index="${i}" data-log="delete">删除</button>
                </li>
            </ul>`;
        }
        renderDom.innerHTML = dataStr;

        // 不同页的数据的渲染，让翻页按钮的样式改变
        var preBtn = document.getElementById('pre-btn'),
            nextBtn = document.getElementById('next-btn');
        if(this.allPage == 1){
            preBtn.style.backgroundColor = '#ccc';
            nextBtn.style.backgroundColor = '#ccc';
        }else if(this.page == 1) {
            preBtn.style.backgroundColor = '#ccc';
            nextBtn.style.backgroundColor = '';
        }else if(this.page == this.allPage){
            preBtn.style.backgroundColor = '';
            nextBtn.style.backgroundColor = '#ccc';
        }
    },
    editEvent: function() {
        var ulParent = document.getElementsByClassName('student-list')[0];
        var maskDiv = document.getElementsByClassName('mask')[0];
        // console.log(ulParent);
        var that = this;
        ulParent.onclick = function(e) {
            var event = e || window.event;
            var target = event.target || event.srcElement;
            if(target.getAttribute('data-log') == 'edit'){
                // console.log('edit');
                maskDiv.style.display = 'block';
                var index = target.getAttribute('data-index');
                var editData = that.tableData[index];
                // console.log(editData);
                that.renderEditForm(editData);

            }else if(target.getAttribute('data-log') == 'delete'){
                // console.log('delete');
                index = target.getAttribute('data-index');
                editData = that.tableData[index];
                var isDelete = window.confirm('确定要删除此学生信息吗？');
                if(isDelete) {
                    var delSNo = {
                        sNo: editData.sNo
                    }
                    ajax('GET', 'http://open.duyiedu.com/api/student/delBySno', that.dataConcat(delSNo), function(res){
                        // console.log(res);
                        if(res.status == 'success'){
                            // that.page = 1;
                            alert(res.msg);
                            that.getTableData();
                        }else{
                            alert(res.msg);
                        }
                    }, true);
                }

            }
        }

        var editBtn = document.getElementById('edit-sub');
        var formElement = document.getElementsByClassName('edit-student')[0];
        editBtn.onclick = function(e) {
            var event = e || window.event;
            event.preventDefault();
            var stuInf = {  
                name: formElement.editName.value,
                // 可以通过form. id || name 访问form下面的元素，如果有多个，返回类数组，里面带有value值
                sex: formElement.editSex.value,
                email: formElement.editTheemail.value,
                sNo: formElement.editNumber.value,
                birth: formElement.editYear.value,
                phone: formElement.editPhone.value,
                address: formElement.editAddress.value
            };
            var bool = true;
            for(var prop in stuInf) {
                bool = bool && stuInf[prop];
            }
            if(bool) {
                // 学号必须为 4 - 16 位的数字
                var regSNo = /^\d{4,16}$/;
                if(regSNo.test(stuInf.sNo)){
                    // 校验出生年份 1920 - 2020
                    if(stuInf.birth >= 1920 && stuInf.birth <= 2020 && stuInf.birth.length == 4){
                        // 校验手机号
                        if(/^1\d{10}$/.test(stuInf.phone)){
                            ajax('GET', 'http://open.duyiedu.com/api/student/updateStudent', that.dataConcat(stuInf), function(res){
                                // console.log(res);
                                if(res.status == 'success') {
                                    alert(res.msg);
                                    that.getTableData();
                                    maskDiv.style.display = 'none';
                                }else{
                                    alert(res.msg);
                                }
                            }, true);
                        }else {
                            alert('请检查手机号是否正确');
                        }
                    }else{
                        alert('请检查出生年是否正确');
                    }
                }else{
                    alert('Sorry, 学号必须为 4 - 16 位的数字！');
                }
            }else{
                alert('表单填写不完整，请认真检查一下呀！');
            }
        }
        var closeBtn = document.getElementsByClassName('closeBtn')[0];
        closeBtn.onclick = function() {
            maskDiv.style.display = 'none';
        }
    },
    renderEditForm: function(editData) {
        var formElement = document.getElementsByClassName('edit-student')[0];
        formElement.editName.value = editData.name;
        formElement.editSex.value = editData.sex;
        formElement.editTheemail.value = editData.email;
        formElement.editNumber.value = editData.sNo;
        formElement.editYear.value = editData.birth
        formElement.editPhone.value = editData.phone;
        formElement.editAddress.value = editData.address;

    }   
}

indexObj.init();
